//
//  UserInfoViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/8/22.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "UserInfoViewController.h"
#import "AvatarTableViewCell.h"
#import "DTPickerManager.h"
#import "SetUserInfoApi.h"
#import "GetUserInfoApi.h"
#import "NSDate+DateTools.h"


@interface UserInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (strong, nonatomic) NSMutableDictionary *userInfoDic;
@property (nonatomic, strong) UIImagePickerController * imagePicker; // 系统图片框架


@end

@implementation UserInfoViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getUserInfomation];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    
}

- (void)refreshBaseControlValue
{
//    [self masLayoutSubviews];
    
}

#pragma mark - 点击事件


#pragma mark - 事件处理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    NSLog(@"buttonindex===%ld",(long)buttonIndex);
    switch (buttonIndex) {
        case 0:
            
        {
            [self formcamera];
            
        }
            break;
        case 1:
            
        {
            [self formphoto];
        }
            break;
            
        default:
            break;
    }
}

-(void)formcamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing=YES;
        _imagePicker = imagePicker;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else{
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:MyNSLocalizedString(@"提示") message:MyNSLocalizedString(@"设备不可用") delegate:self cancelButtonTitle:MyNSLocalizedString(@"确定") otherButtonTitles:nil, nil];
        [alert show];
        
    }
}
-(void)formphoto
{
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    _imagePicker = imagePicker;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate
// 完成选择
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];  // 取出被编辑的图片
    NSData * imageData = UIImageJPEGRepresentation(image, 1.0f);
    [[NSFileManager defaultManager]removeItemAtPath:PicPath(UID) error:nil];
    
    if (imageData.length > 100 * 1024) {
        if (imageData.length > 1000 * 1024) {
            [UIImageJPEGRepresentation(image, 0.2f) writeToFile:PorPath atomically:YES];
        } else {
            [UIImageJPEGRepresentation(image, 0.4f) writeToFile:PorPath atomically:YES];
        }
    } else {
        [UIImageJPEGRepresentation(image, 1.0f) writeToFile:PorPath atomically:YES];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
    SetUserInfoApi * setApi = [[SetUserInfoApi alloc] initWithInfo:@{@"image":PorPath}];
    [setApi dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        if ([[request responseJSONObject][@"errcode"] intValue] == 0) {
            GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
            [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                [userInfoApi analyseResponseObject];
                [self.tableView reloadData];
                [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"修改成功")];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfo" object:nil];
            } failure:^(YTKBaseRequest *request) {
                [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"请求超时")];
            }];
        }
    } failure:nil];
    
}

// 取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)updateUserInfo
{
    SetUserInfoApi *api = [[SetUserInfoApi alloc]initWithInfo:_userInfoDic];
    [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        NSDictionary *dic = request.responseJSONObject;
        if ([dic[@"errcode"]intValue] == 0) {
            GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
            [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                [userInfoApi analyseResponseObject];
                [self userInfoDic];
                [self.tableView reloadData];
                [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"修改成功")];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfo" object:nil];
            } failure:^(YTKBaseRequest *request) {
                [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"请求超时")];
            }];
        }
    } failure:nil];

}

- (NSMutableDictionary *)userInfoDic
{
    if (!_userInfoDic) {
        _userInfoDic = [[NSMutableDictionary alloc]init];
    }
    
    NSArray *array = @[@"nickname",@"username",@"sex"
                       ,@"height",@"weight",@"birthday",@"image",@"wsy_uid"];
    NSDictionary *infoDic = EXRACT_OBJECT(INFODIC);
    for (NSString *key in array) {
        if ([infoDic[key]length] == 0) {
            [_userInfoDic setValue:@"" forKey:key];
        }else{
            [_userInfoDic setValue:infoDic[key] forKey:key];
        }
    }
    
    return _userInfoDic;
}

- (void)getUserInfomation
{
    GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
    [userInfoApi dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        [userInfoApi analyseResponseObject];
        [self userInfoDic];
        [self.tableView reloadData];
    } failure:nil];
    
}


#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return px1920Height(323);
    } else {
        return px1920Height(156);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.row == 0)
    {
        AvatarTableViewCell *cell = [AvatarTableViewCell dequeueReusableWithTableView:tableView];
        cell.avatarView.image = [UIImage imageNamed:@"avatar"];
        [cell.avatarView sd_setImageWithURL:[NSURL URLWithString:EXRACT_OBJECT(IMAGE)] placeholderImage:[UIImage imageNamed:@"icon_tacitly"]];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    else
    {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"UserInfoTableViewCell"];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = self.titleArray[indexPath.row];
//        cell.detailTextLabel.text = self.dataArray[indexPath.row];
        if (indexPath.row == 1)
        {
            cell.detailTextLabel.text = self.userInfoDic[@"nickname"];
        }
        else if (indexPath.row == 2)
        {
            if ([self.userInfoDic[@"sex"]isEqualToString:@"1"]) {
                cell.detailTextLabel.text = MyNSLocalizedString(@"男");
            }else if ([self.userInfoDic[@"sex"]isEqualToString:@"2"]) {
                cell.detailTextLabel.text = MyNSLocalizedString(@"女");
            }else{
                cell.detailTextLabel.text = MyNSLocalizedString(@"");
            }
        }
        else if (indexPath.row == 3)
        {
            cell.detailTextLabel.text = self.userInfoDic[@"birthday"];
        }
        else if (indexPath.row == 4)
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@cm",self.userInfoDic[@"height"]];
        }
        else if (indexPath.row == 5)
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@kg",self.userInfoDic[@"weight"]];
        }
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.textLabel.textColor = [UIColor darkGrayColor];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.hidesBottomBarWhenPushed = YES;
    if (indexPath.row == 0)
    {
        
        UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:MyNSLocalizedString(@"设置头像") delegate:self cancelButtonTitle:MyNSLocalizedString(@"取消") destructiveButtonTitle:MyNSLocalizedString(@"拍摄照片") otherButtonTitles:MyNSLocalizedString(@"相册"), nil] ;
        [sheet showInView:self.view];
    }
    else if (indexPath.row == 1)
    {
        [[AlertViewManager shareManager] initWithEditActionTitle:MyNSLocalizedString(@"重命名") message:nil cancleButtonTitle:MyNSLocalizedString(@"取消") OtherButtonsArray:@[MyNSLocalizedString(@"确认")] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
            if (buttonIndex == 1) {
                if (alertController.textFields.firstObject.text.length == 0) {
                    [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"名字不能为空")];
                    return;
                }
                if (alertController.textFields.firstObject.text.length > 10) {
                    [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"设备名称不能超过20个字符")];
                    return;
                }

                if ([NSString isContainsTwoEmoji:alertController.textFields.firstObject.text] ) {
                    [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"名字不能使用表情")];
                    return;
                }
                NSString *string = [alertController.textFields.firstObject.text stringByReplacingOccurrencesOfString:@" " withString:@""];
                [self.userInfoDic setValue:string forKey:@"nickname"];
                
                [self updateUserInfo];
            }
        }];
        
    }
    else if (indexPath.row == 2)
    {
        [[DTPickerManager shareManager]showPickerWithSexAndPicker:^(NSArray *arr) {
            
        } andConfirm:^(NSArray *arr) {
            if ([arr[0] isEqualToString:MyNSLocalizedString(@"男")]) {
                [self.userInfoDic setValue:@"1" forKey:@"sex"];
            }else if ([arr[0] isEqualToString:MyNSLocalizedString(@"女")]){
                [self.userInfoDic setValue:@"2" forKey:@"sex"];
            }
            
            [self updateUserInfo];
        }];
    }
    else if (indexPath.row == 3)
    {
        NSDate *date = [NSDate date];
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSArray *valueList = [cell.detailTextLabel.text componentsSeparatedByString:@"-"];
        NSMutableArray *array = [NSMutableArray array];
        for (NSString *str in valueList) {
            [array addObject:@(str.intValue).stringValue];
        }
        if (array.count == 3) {
            date = [NSDate dateWithString:[NSString stringWithFormat:@"%.4d%.2d%.2d",[array[0] intValue],[array[1] intValue],[array[2] intValue]] formatString:@"yyyyMMdd"];
        }
        
        [[DTPickerManager shareManager]showDate:date pickerWithBirthDayAndPicker:^(NSArray *arr) {
            
        } andConfirm:^(NSArray *arr) {
            [_userInfoDic setValue:[NSString stringWithFormat:@"%.2d-%.2d-%.2d",[arr[0]intValue],[arr[1]intValue],[arr[2]intValue]] forKey:@"birthday"];
            [self updateUserInfo];
        }];
    }
    else if (indexPath.row == 4)
    {
        [[DTPickerManager shareManager]showPickerWithHeightAndPicker:^(NSArray *arr) {
            
        } andConfirm:^(NSArray *arr) {
            [_userInfoDic setValue:@([arr[0]intValue]).stringValue forKey:@"height"];

            [self updateUserInfo];
        }];
       
    }
    else if (indexPath.row == 5)
    {
        [[DTPickerManager shareManager]showPickerWithWeightAndPicker:^(NSArray *arr) {
            
        } andConfirm:^(NSArray *arr) {
            [_userInfoDic setValue:@([arr[0]intValue]).stringValue forKey:@"weight"];

            [self updateUserInfo];
        }];
    }

    

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark - 通知处理



- (void)setNavigationStyle
{
    [self setNavigationBarTitle:MyNSLocalizedString(@"个人信息")];

}

- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.equalTo(superView);
    }];
}


#pragma mark - 初始化
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.scrollEnabled = NO;
        [superView addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
//        _tableView.separatorColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1];
    }
    return _tableView;
}

- (NSArray *)titleArray
{
    if(!_titleArray)
    {
        _titleArray = @[@"",MyNSLocalizedString(@"姓名"),MyNSLocalizedString(@"性别"),MyNSLocalizedString(@"生日"),MyNSLocalizedString(@"身高"),MyNSLocalizedString(@"体重")];
    }
    return _titleArray;
}

//- (NSMutableArray *)dataArray
//{
//    if(!_dataArray)
//    {
//        _dataArray = [[NSMutableArray alloc]init];
//        [_dataArray addObjectsFromArray:@[@"",EXRACT_OBJECT(NICKNAME),@"女",@"1990-03-20",@"168CM",@"50kg"]];
//    }
//    return _dataArray;
//}


@end
